package online.rabbitmq;

import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Auther: 狼芒
 * @Date: 2021/10/24 22:44
 * @Descrintion:RabbitMQ消费者
 * @version: 1.0
 */
@Slf4j
public class Comsumer {

    //队列名称
    private static final String QUEUE_NAMW = "hello";


    //接收消息
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("guest");
        factory.setPassword("guest");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //声明，接收消息
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            log.error("consumerTag:{}, message:{}", consumerTag, new String(message.getBody()));
        };
        //取消消息时回调
        CancelCallback cancleCallback = cancleTag-> {
            log.error("消费中断 cancleTag:{}", cancleTag);
        };
        /**
         * 消费者消费消息
         * 1、消费那一个队列
         * 2、消费成功后，是否自动应答，true为自动应答
         * 3、消费者未成功消费的回调
         * 4、消费者取消消费的回调
         */
        channel.basicConsume(QUEUE_NAMW, true, deliverCallback, cancleCallback);

    }
}
